<template>
  <div>
    <div style="height:6vh;background-color:#fff;padding: 10px 20px;">
      <span style="line-height: 60px;font-size: 20px;">请假申请</span>
      <el-button
          type="primary"
          style="float: right; margin-top: 13px;"
          :disabled="getUser.parentId==null"
          @click="beforeAddApplication">
        请假申请
      </el-button>
    </div>

    <!-- 弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :before-close="handleClose">
      <el-form label-width="80px" label-position="top" :model="applicationForm" :rules="rules" ref="applicationForm">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="请假人" prop="employeeName">
              <el-input v-model="applicationForm.employeeName" disabled placeholder="请输入姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请假类型" prop="type">
              <el-input v-model="applicationForm.type" placeholder="请输入请假类型:事假/病假等"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间">
              <el-date-picker
                  type="datetime"
                  placeholder="选择开始时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  v-model="applicationForm.startTime"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间">
              <el-date-picker
                  type="datetime"
                  placeholder="选择结束时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  v-model="applicationForm.endTime"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="请假原因" prop="reason">
              <el-input v-model="applicationForm.reason"
                        placeholder="请输入请假原因"
                        style="width:100%"
                        type="textarea"
                        :rows="3">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批人">
                <div style="display: inline-block; margin: 0 5px 5px 0" v-if="auditEmployeeOpts.length>0" v-for="(item, index) in auditEmployeeOpts">
                  <el-tag type="primary">
                    <span>{{ item.name }}</span>
                  </el-tag>
                </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 查询条件 -->
    <el-card style="margin: 20px;">
      <el-form :inline="true" @submit.native.prevent>
        <el-form-item label="请假人姓名">
          <el-input v-model="searchForm.employeeName" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" clearable placeholder="请选择状态">
            <el-option label="已发起" :value=1></el-option>
            <el-option label="撤销" :value=2></el-option>
            <el-option label="审核中" :value=3></el-option>
            <el-option label="驳回" :value=4></el-option>
            <el-option label="已通过" :value=5></el-option>
            <el-option label="已销假" :value=6></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="loadApplicationList">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card style="margin: 20px;">
      <el-table :data="applicationList">
        <el-table-column label="编号" type="index" align="center"></el-table-column>
        <el-table-column label="申请人" prop="employeeName" align="center"></el-table-column>
        <el-table-column label="请假类型" prop="type" align="center"></el-table-column>
        <el-table-column label="开始时间" prop="startTime" align="center"></el-table-column>
        <el-table-column label="结束时间" prop="endTime" align="center"></el-table-column>
        <el-table-column label="请假原因" prop="reason" align="center"></el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="{row}">
            <el-tag :type="statusTagType(row.status)">
              {{ formatStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审批意见" align="center">
          <template #default="{row}">
              {{ row.comments ? row.comments : '无'}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right">
          <template #default="{row}">
            <el-button type="primary" size="small" link
                       :disabled="getUser.id !== row.employeeId || row.status !== 1" @click="cancel(row.id)">撤销</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.current"
          :page-sizes="[3, 4, 5]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          style="margin-top: 20px;">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import {Message} from 'element-ui';
import qs from "qs";

export default {
  data() {
    return {
      getUser: this.$getUser(),
      dialogVisible: false,
      dialogTitle: '新增申请单',
      applicationForm: {
        id: null,
        employeeId: this.$getUser().id,
        employeeName: this.$getUser().name,
        type: null,
        startTime: '',
        endTime: '',
        reason: ''
      },
      searchForm: {
        employeeName: '',
        status: ''
      },
      applicationList: [],
      auditEmployeeOpts: [],
      auditEmployeeIdList: [],
      pagination: {
        current: 1,
        size: 3,
        total: 0
      },
      rules: {
        type: [
          {required: true, message: '请选择请假类型', trigger: 'blur'}
        ],
        startTime: [
          {required: true, message: '请选择时间', trigger: 'change'}
        ],
        endTime: [
          {required: true, message: '请选择时间', trigger: 'change'}
        ],
        reason: [
          {required: true, message: '请输入请假原因', trigger: 'blur'}
        ]
      }
    };
  },
  mounted() {
    this.loadApplicationList();
  },
  methods: {
    // 加载请假列表
    loadApplicationList() {
      const data = qs.stringify({
        pageCurrent: this.pagination.current,
        pageSize: this.pagination.size,
        ...this.searchForm
      });
      axios.get(this.$BASE_URL + '/v1/application/list?'+data)
          .then(res => {
            console.log(res.data)
            if (res.data.state === 2000) {
              this.applicationList = res.data.data.applicationList;
              this.pagination.total = res.data.data.total;
            }else {
              Message.error(res.data.msg);
            }
          })
    },

    loadAuditUser() {
      //获取当前登录人的直属领导id
      let parentId = this.getUser.parentId;
      //根据此直属领导id查出对应的领导数据
      axios.get(this.$BASE_URL+'/v1/user/list/audit/'+parentId)
          .then((res)=>{
            console.log(res.data)
            if(res.data.state===2000){
              this.auditEmployeeOpts = res.data.data;
              //遍历上方的审批人数组,取出当前审批人id,存入审批人id数组中
              for(let i=0;i<this.auditEmployeeOpts.length;i++){
                this.auditEmployeeIdList.push(this.auditEmployeeOpts[i].id);
              }
            }else{
              Message.error(res.data.msg);
            }
          })
    },

    // 状态显示格式化
    formatStatus(status) {
      const map = {1: '已发起', 2: '撤销', 3: '审核中', 4: '驳回', 5: '已通过', 6: '已销假'};
      return map[status];
    },

    statusTagType(status) {
      const types = {1: 'success', 2: 'info', 3: 'warning', 4: 'danger', 5: 'success', 6: 'info'};
      return types[status] || '';
    },

    // 提交候选人数据
    submit() {
      this.$refs.applicationForm.validate(valid => {
        if (valid) {
          this.applicationForm.auditEmployeeIdList = this.auditEmployeeIdList;
          axios.post(this.$BASE_URL + '/v1/application/save', qs.stringify(this.applicationForm))
              .then(res => {
                if (res.data.state === 2000) {
                  Message.success('操作成功');
                  this.dialogVisible = false;
                  this.loadApplicationList();
                }else {
                  Message.error(res.data.msg);
                }
              });
        }
      });
    },

    // 新增申请单
    beforeAddApplication() {
      this.dialogTitle = '新增申请单';
      this.dialogVisible = true;
      this.applicationForm = {
        id: null,
        employeeId: this.getUser.id,
        employeeName: this.getUser.name,
        type: null,
        startTime: '',
        endTime: '',
        reason: ''
      };
      this.loadAuditUser();
    },

    // 撤销申请
    cancel(id) {
      this.$confirm('确定撤销该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        axios.post(this.$BASE_URL + '/v1/application/cancel/' + id)
            .then((res)=>{
              if(res.data.state===2000){
                Message.success('操作成功');
                this.loadApplicationList();
              }else{
                Message.error(res.data.msg);
              }
            })
      });
    },

    // 重置查询
    resetSearch() {
      this.searchForm = {};
      this.pagination.current = 1;
      this.loadApplicationList();
    },

    // 分页处理
    handleSizeChange(size) {
      this.pagination.size = size;
      this.loadApplicationList();
    },

    handleCurrentChange(current) {
      this.pagination.current = current;
      this.loadApplicationList();
    },

    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false;
      this.applicationForm = {
        id: null,
        employeeId: this.getUser.id,
        employeeName: this.getUser.name,
        type: null,
        startTime: '',
        endTime: '',
        reason: ''
      };
    }
  }
};
</script>

<style scoped>
.el-form-item {
  margin-bottom: 0;
}
</style>